import React, { useState, useEffect } from "react";
import { Table, DatePicker, Select, Button, Flex, Input } from "antd";
import "./orderManage.css";
import useCloseLoadingOnMount from "../../../utils/hook/useCloseLoadingOnMount";
import ordersApi from "../../../apis/ordersApi";
import { hb } from "../../../utils/common";
import { Empty } from "antd";

const { RangePicker } = DatePicker;
const { Option } = Select;

// 模拟数据获取函数，根据 RequestOrdersDto 调整
const fetchOrders = async (key, status) => {
  var d = await ordersApi.getOrdersPagination({
    page: 1,
    limit: 10,
    key: key,
    statuss: status,
  });
  return {
    data: d.data.data,
    total: d.data.total,
  };
};

// 表格列定义，根据 RequestOrdersDto 调整
const columns = [
  {
    title: "编号",
    dataIndex: "id",
    width: 80,
  },
  {
    title: "商家",
    dataIndex: "businessName",
    width: 120,
  },
  {
    title: "供应商",
    dataIndex: "supplierName",
    width: 120,
  },
  {
    title: "订单状态",
    dataIndex: "status",
    width: 120,
    filters: [
      { text: "已接单未发货", value: 0 },
      { text: "已发货", value: 1 },
      { text: "已收货", value: 2 },
      { text: "全部完成", value: 3 },
      { text: "部分完成", value: 4 },
      { text: "已拒收", value: 5 },
    ],
    render: (status) => {
      const statusMap = {
        4: "未接单",
        5: "待发货",
        6: "已发货",
        7: "全部完成",
        8: "部分完成",
        3: "供应商拒绝接单",
        2: "商家取消",
        1: "供应商取消",
        0: "已拒收",
      };
      return statusMap[status + 4];
    },
  },
  {
    title: "接单时间",
    dataIndex: "acceptOrderTimeStr",
    width: 180,
    sorter: (a, b) => new Date(a.acceptOrderTime) - new Date(b.acceptOrderTime),
  },
  {
    title: "发货时间",
    dataIndex: "sendTimeStr",
    width: 180,
  },
  {
    title: "收货时间",
    dataIndex: "receiveTimeStr",
    width: 180,
  },
  {
    title: "完成时间",
    dataIndex: "completeTimeStr",
    width: 180,
  },
  {
    title: "实付金额",
    dataIndex: "payMoney",
    width: 120,
    render: (payMoney) => `¥${payMoney?.toFixed(2)}`,
  },
  {
    title: "供应商备注",
    dataIndex: "supplierMarkup",
    width: 200,
  },
  {
    title: "商家备注",
    dataIndex: "businessMarkup",
    width: 120,
  },
];

const LogManage = () => {
  useCloseLoadingOnMount();
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [flag, setFlag] = useState(false);
  const [filter, setFilter] = useState({
    timeRange: [],
    status: null,
  });
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
    key: "",
  });

  const bind = async () => {
    setLoading(true);
    try {
      const res = await fetchOrders(pagination.key, filter.status);
      setData(res.data);
      setPagination({ ...pagination, total: res.total });
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    bind();
  }, [pagination.current]);

  useEffect(() => {
    if (flag) {
      if (pagination.current != 1) {
        setPagination({ ...pagination, current: 1 });
      } else {
        bind();
      }
    }
    setFlag(true);
  }, [pagination.pageSize, pagination.key, filter.status]);

  return (
    <div className="body-container1">
      <Flex className="search-bar" align="center">
        <Input
          style={{ width: "200px" }}
          placeholder="请输入商家或供应商名称"
          value={pagination.key}
          onChange={(e) => {
            setPagination({
              ...pagination,
              key: e.target.value,
            });
          }}
        ></Input>
        <RangePicker
          showTime
          onChange={(dates) =>
            setFilter((prev) => ({ ...prev, timeRange: dates }))
          }
          style={{ width: 320 }}
        />
        <Select
          placeholder="选择订单状态"
          allowClear
          style={{ width: 160 }}
          onChange={(value) =>
            setFilter((prev) => ({ ...prev, status: parseInt(value) }))
          }
        >
          <Option value="0">未接单</Option>
          <Option value="1">待发货</Option>
          <Option value="2">已发货</Option>
          <Option value="3">全部完成</Option>
          <Option value="4">部分完成</Option>
          <Option value="-1">供应商拒绝接单</Option>
          <Option value="-2">商家取消</Option>
          <Option value="-3">供应商取消</Option>
          <Option value="-4">已拒收</Option>
        </Select>
        <Button type="primary" onClick={() => setFilter({ ...filter })}>
          查询
        </Button>
      </Flex>

      <Table
        locale={{ emptyText: <Empty description="暂无数据"></Empty> }}
        className="log-table"
        columns={columns.map((d) => {
          if (d.render == null) {
            return { ...d, render: (text) => hb(text) };
          } else {
            return d;
          }
        })}
        dataSource={data}
        loading={loading}
        rowKey="id"
        scroll={{ x: "max-content" }}
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          pageSizeOptions: ["5", "10", "20", "50"],
        }}
        onPageChange={(page, pageSize) => {
          setPagination({
            ...pagination,
            current: page,
            pageSize,
          });
        }}
      />
    </div>
  );
};

export default LogManage;
